package com.heima.behavior.service.impl;

import com.heima.behavior.service.IApBehaviorEntryService;
import com.heima.behavior.service.IApLikeBehaviorService;
import com.heima.model.behavior.dtos.LikeBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class ApLikeBehaviorService implements IApLikeBehaviorService {

    @Autowired
    private IApBehaviorEntryService apBehaviorEntryService;
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public ResponseResult handleLike(LikeBehaviorDTO likeBehaviorDTO) {
        //1.校验参数
            //1.1校验登录状态(点赞行为必须为用户登录，不能是设备登录)
        Integer userId = AppThreadLocalUtils.getUser();
        if(userId == null || userId.intValue() == 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN, "电站行为需要先账号登录");
        }
            //1.2获取用户行为实体
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(userId, likeBehaviorDTO.getEquipmentId());
        if(apBehaviorEntry == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "获取当前用户行为实体信息失败");
        }
            //1.3避免重复点赞
        Query query = Query.query(Criteria.where("entry_id").is(apBehaviorEntry.getId()).and("article_id").is(likeBehaviorDTO.getArticleId()));
        ApLikesBehavior apLikesBehavior = mongoTemplate.findOne(query, ApLikesBehavior.class);
        if(likeBehaviorDTO.getOperation().intValue() == 0 && apLikesBehavior != null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_ALLOW, "已点赞，请勿重复点赞");
        }
        //2.处理点赞行为
        if(likeBehaviorDTO.getOperation().intValue() == 0){
            //2.1保存点赞行为
            ApLikesBehavior newApLikesBehavior = new ApLikesBehavior();
            newApLikesBehavior.setEntryId(apBehaviorEntry.getId());
            newApLikesBehavior.setArticleId(likeBehaviorDTO.getArticleId());
            newApLikesBehavior.setType((short) 0);  //文章
            newApLikesBehavior.setOperation((short) 0); //点赞
            newApLikesBehavior.setCreatedTime(new Date());
            mongoTemplate.save(newApLikesBehavior);
        }else{
            //2.2删除点赞行为
            mongoTemplate.remove(query, ApLikesBehavior.class);
        }
        //3.返回响应
        return ResponseResult.okResult();
    }
}
